package com.battcn.config;

import com.battcn.vo.module.ApiParamType;
import com.fasterxml.classmate.TypeResolver;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.async.DeferredResult;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.schema.WildcardType;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.ApiKeyVehicle;
import springfox.documentation.swagger.web.SecurityConfiguration;
import springfox.documentation.swagger.web.UiConfiguration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

import static springfox.documentation.schema.AlternateTypeRules.newRule;

/**
 * @author fly
 * @ClassName: Swagger2Config
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @date 2017年2月23日
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Bean
    public Docket petApi() {
        List<ResponseMessage> messages = new ArrayList<>();
        ResponseMessage message1 = new ResponseMessageBuilder().code(200).message("操作成功").responseModel(new ModelRef("操作成功")).build();
        ResponseMessage message2 = new ResponseMessageBuilder().code(400).message("非法请求").responseModel(new ModelRef("非法请求")).build();
        ResponseMessage message3 = new ResponseMessageBuilder().code(501).message("如请求路径拼写不正确").responseModel(new ModelRef("如请求路径拼写不正确")).build();
        ResponseMessage message4 = new ResponseMessageBuilder().code(502).message("服务器过载引起的错误").responseModel(new ModelRef("服务器过载引起的错误")).build();
        messages.add(message1);
        messages.add(message2);
        messages.add(message3);
        messages.add(message4);
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("battcn-swagger")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.battcn.controller"))
                .paths(PathSelectors.any())
                .build()
                .pathMapping("/")
                .directModelSubstitute(LocalDate.class, String.class)
                .genericModelSubstitutes(ResponseEntity.class)
                .alternateTypeRules(
                        newRule(typeResolver.resolve(DeferredResult.class,
                                typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
                                typeResolver.resolve(WildcardType.class)))
                .useDefaultResponseMessages(false)
                .globalResponseMessage(RequestMethod.POST, messages)
                .securitySchemes(apiKeys())
                .securityContexts(securityContext())
                //.globalOperationParameters(newArrayList(new ParameterBuilder().name("someGlobalParameter").description("Description of someGlobalParameter").modelRef(new ModelRef("string")).parameterType("query").required(true).build()))
                //.additionalModels(typeResolver.resolve(AdditionalModel.class))
                ;
    }

    private List<ApiKey> apiKeys() {
        List<ApiKey> list = Lists.newArrayList();
        list.add(new ApiKey("battcn", "battcn", ApiParamType.HEADER));
        return list;
    }

    private List<SecurityContext> securityContext() {
        List list = Lists.newArrayList();
        list.add(SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex("/.*?"))
                .build());
        return list;
    }

    List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "描述内容");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[]{authorizationScope};
        return Lists.newArrayList(new SecurityReference("battcn", authorizationScopes));
    }

    @Autowired
    private TypeResolver typeResolver;
    @Bean
    SecurityConfiguration security() {
        return new SecurityConfiguration(
                "battcn-swagger-app-client-id",
                "battcn-swagger-client-secret",
                "battcn-swagger-realm",
                "battcn-swagger",
                "battcn",
                ApiKeyVehicle.HEADER,
                "battcn",
                "," /*scope separator*/);
    }
    @Bean
    UiConfiguration uiConfig() {
        return new UiConfiguration(
                "/",// url
                "list",       // docExpansion          => none | list
                "alpha",      // apiSorter             => alpha
                "schema",     // defaultModelRendering => schema
                UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS,
                false,        // enableJsonEditor      => true | false
                true,         // showRequestHeaders    => true | false
                60000L);      // requestTimeout => in milliseconds, defaults to null (uses jquery xh timeout)
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2")
                .description("Battcn Swagger")
                .termsOfServiceUrl("http://www.battcn.com")
                .contact(new Contact("唐亚峰", "http://www.battcn.com", "1837307557@qq.com"))
                .version("3.0")
                .license("点击有喜")
                .licenseUrl("http://www.battcn.com")
                .build();
    }
}
